import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import Utils from 'src/utils/Utils';
import { Repository } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private user: Repository<User>,
  ) { }

  create(createUserDto: CreateUserDto) {
    createUserDto.guid = Utils.guid();
    createUserDto.salt = Utils.getSalt();
    createUserDto.password = Utils.MD5(createUserDto.password, createUserDto.salt);
    return this.user.save(createUserDto);
  }

  findAll() {
    return `This action returns all user`;
  }

  async findOneByMobile(mobile: string) {
    const user = await this.user.findOne({ where: { mobile, delete: false } });
    if (!user?.guid) throw '未查询到该用户~'
    return user
  }

  async findOneByGuid(guid: string) {
    const user = await this.user.findOne({ where: { guid, delete: false } })
    if (!user?.guid) throw '未查询到该用户~'
    return user
  }

  async update(dto: UpdateUserDto) {
    const { guid, userName, mobile, password, rePassword } = dto
    const user = await this.findOneByGuid(guid);
    if (!user?.guid) throw '未查询到该用户~'
    if (!user.status) throw '当前注册账号未审核通过~'
    // 更新密码
    const updateObj = {}
    if (password && rePassword) {
      const md5 = Utils.MD5(password, user.salt);
      if (md5 !== user.password) throw '登录密码错误~'
      if (rePassword.length < 6) throw '密码位数过少~'
      const newPWD = Utils.MD5(rePassword, user.salt)
      return await this.user.update({ guid }, {
        password: newPWD,
        updateTime: new Date(),
      })
    } else {
      // 更新信息
      return await this.user.update({ guid }, {
        userName: userName || user.userName,
        mobile: mobile || user.mobile,
        updateTime: new Date()
      })
    }
  }

  remove(id: string) {
    return `This action removes a #${id} user`;
  }
}
